/*!
 * \file test_strategy_and_factory_comprehensive.cpp
 * \brief 策略和工厂模块综合测试
 * 
 * \details 本文件包含对WonderTrader项目中策略工厂、执行器工厂、
 *          风险管理工厂等模块的综合测试，提升这些模块的测试覆盖率
 * 
 * \author WonderTrader测试团队
 * \date 2024-12-15
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <functional>
#include <atomic>
#include <thread>
#include <mutex>
#include <chrono>

using namespace std;
using ::testing::_;
using ::testing::Return;
using ::testing::AtLeast;

/*!
 * \class StrategyAndFactoryTest
 * \brief 策略和工厂模块综合测试类
 * 
 * \details 测试策略工厂、执行器工厂、风险管理工厂等模块
 */
class StrategyAndFactoryTest : public ::testing::Test {
protected:
    void SetUp() override {
        test_start_time = std::chrono::high_resolution_clock::now();
    }
    
    void TearDown() override {
        auto test_end_time = std::chrono::high_resolution_clock::now();
        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(
            test_end_time - test_start_time);
        
        if (duration.count() > 50000) {  // 超过50ms记录
            std::cout << "测试执行时间: " << duration.count() << "us" << std::endl;
        }
    }

protected:
    std::chrono::high_resolution_clock::time_point test_start_time;
};

// ========== CTA策略工厂测试 ==========

/*!
 * \brief 测试CTA策略工厂功能
 * 
 * \details 模拟WtCtaStraFact模块的策略创建和管理功能
 */
TEST_F(StrategyAndFactoryTest, TestCtaStrategyFactory) {
    // 模拟CTA策略接口
    struct ICtaStrategy {
        std::string strategy_name;
        std::map<std::string, std::string> parameters;
        bool initialized = false;
        bool started = false;
        std::atomic<int> signal_count{0};
        
        virtual ~ICtaStrategy() = default;
        
        virtual bool init(const std::map<std::string, std::string>& params) {
            parameters = params;
            initialized = true;
            return true;
        }
        
        virtual bool start() {
            if (!initialized) return false;
            started = true;
            return true;
        }
        
        virtual void stop() {
            started = false;
        }
        
        virtual void onBar(const std::string& symbol, int timeframe) {
            if (started) {
                signal_count++;
                // 模拟策略信号生成
                processSignal(symbol, timeframe);
            }
        }
        
        virtual void onTick(const std::string& symbol, double price, int volume) {
            if (started) {
                // 模拟tick数据处理
                processTick(symbol, price, volume);
            }
        }
        
        bool isInitialized() const { return initialized; }
        bool isStarted() const { return started; }
        int getSignalCount() const { return signal_count.load(); }
        
    protected:
        virtual void processSignal(const std::string& symbol, int timeframe) {
            // 子类实现具体的信号处理逻辑
        }
        
        virtual void processTick(const std::string& symbol, double price, int volume) {
            // 子类实现具体的tick处理逻辑
        }
    };
    
    // 模拟具体的CTA策略实现
    struct DualThrustStrategy : public ICtaStrategy {
        double upper_threshold = 0.7;
        double lower_threshold = 0.3;
        std::vector<double> price_history;
        
        DualThrustStrategy() {
            strategy_name = "DualThrust";
        }
        
        bool init(const std::map<std::string, std::string>& params) override {
            if (!ICtaStrategy::init(params)) return false;
            
            auto it = params.find("upper_threshold");
            if (it != params.end()) {
                upper_threshold = std::stod(it->second);
            }
            
            it = params.find("lower_threshold");
            if (it != params.end()) {
                lower_threshold = std::stod(it->second);
            }
            
            return validateParameters();
        }
        
    protected:
        void processSignal(const std::string& symbol, int timeframe) override {
            // 模拟双推策略信号处理
            if (price_history.size() >= 20) {
                double high = *std::max_element(price_history.end() - 20, price_history.end());
                double low = *std::min_element(price_history.end() - 20, price_history.end());
                double range = high - low;
                
                // 简化的双推信号逻辑
                if (range > upper_threshold) {
                    generateBuySignal(symbol);
                } else if (range < lower_threshold) {
                    generateSellSignal(symbol);
                }
            }
        }
        
        void processTick(const std::string& symbol, double price, int volume) override {
            price_history.push_back(price);
            if (price_history.size() > 100) {
                price_history.erase(price_history.begin());
            }
        }
        
    private:
        bool validateParameters() {
            return upper_threshold > lower_threshold && 
                   upper_threshold > 0 && lower_threshold >= 0;
        }
        
        void generateBuySignal(const std::string& symbol) {
            // 模拟买入信号生成
        }
        
        void generateSellSignal(const std::string& symbol) {
            // 模拟卖出信号生成
        }
    };
    
    // 模拟CTA策略工厂
    struct CtaStrategyFactory {
        std::map<std::string, std::function<std::unique_ptr<ICtaStrategy>()>> creators;
        std::vector<std::unique_ptr<ICtaStrategy>> created_strategies;
        
        void registerStrategy(const std::string& name, 
                            std::function<std::unique_ptr<ICtaStrategy>()> creator) {
            creators[name] = creator;
        }
        
        std::unique_ptr<ICtaStrategy> createStrategy(const std::string& name) {
            auto it = creators.find(name);
            if (it != creators.end()) {
                auto strategy = it->second();
                return strategy;
            }
            return nullptr;
        }
        
        std::vector<std::string> getAvailableStrategies() const {
            std::vector<std::string> names;
            for (const auto& pair : creators) {
                names.push_back(pair.first);
            }
            return names;
        }
        
        size_t getRegisteredCount() const {
            return creators.size();
        }
    };
    
    // 测试策略工厂功能
    CtaStrategyFactory factory;
    
    // 注册策略
    factory.registerStrategy("DualThrust", []() {
        return std::make_unique<DualThrustStrategy>();
    });
    
    EXPECT_EQ(factory.getRegisteredCount(), 1);
    
    auto available_strategies = factory.getAvailableStrategies();
    EXPECT_EQ(available_strategies.size(), 1);
    EXPECT_EQ(available_strategies[0], "DualThrust");
    
    // 创建策略实例
    auto strategy = factory.createStrategy("DualThrust");
    ASSERT_NE(strategy, nullptr);
    EXPECT_EQ(strategy->strategy_name, "DualThrust");
    EXPECT_FALSE(strategy->isInitialized());
    EXPECT_FALSE(strategy->isStarted());
    
    // 初始化策略
    std::map<std::string, std::string> params = {
        {"upper_threshold", "0.8"},
        {"lower_threshold", "0.2"}
    };
    EXPECT_TRUE(strategy->init(params));
    EXPECT_TRUE(strategy->isInitialized());
    
    // 启动策略
    EXPECT_TRUE(strategy->start());
    EXPECT_TRUE(strategy->isStarted());
    
    // 测试策略信号处理
    strategy->onBar("SHFE.rb2501", 60);
    strategy->onTick("SHFE.rb2501", 4500.0, 100);
    EXPECT_EQ(strategy->getSignalCount(), 1);
    
    // 停止策略
    strategy->stop();
    EXPECT_FALSE(strategy->isStarted());
    
    // 测试无效策略创建
    auto invalid_strategy = factory.createStrategy("NonExistent");
    EXPECT_EQ(invalid_strategy, nullptr);
}

// ========== 高频策略工厂测试 ==========

/*!
 * \brief 测试高频策略工厂功能
 * 
 * \details 模拟WtHftStraFact模块的高频策略创建和管理功能
 */
TEST_F(StrategyAndFactoryTest, TestHftStrategyFactory) {
    // 模拟高频策略接口
    struct IHftStrategy {
        std::string strategy_name;
        std::map<std::string, std::string> parameters;
        bool initialized = false;
        bool started = false;
        std::atomic<int> order_count{0};
        std::atomic<int> trade_count{0};
        
        virtual ~IHftStrategy() = default;
        
        virtual bool init(const std::map<std::string, std::string>& params) {
            parameters = params;
            initialized = true;
            return true;
        }
        
        virtual bool start() {
            if (!initialized) return false;
            started = true;
            return true;
        }
        
        virtual void stop() {
            started = false;
        }
        
        virtual void onOrderBook(const std::string& symbol, 
                               const std::vector<std::pair<double, int>>& bids,
                               const std::vector<std::pair<double, int>>& asks) {
            if (started) {
                processOrderBook(symbol, bids, asks);
            }
        }
        
        virtual void onTrade(const std::string& symbol, double price, int volume) {
            if (started) {
                trade_count++;
                processTrade(symbol, price, volume);
            }
        }
        
        virtual void onOrder(const std::string& order_id, const std::string& status) {
            if (started) {
                order_count++;
                processOrder(order_id, status);
            }
        }
        
        bool isInitialized() const { return initialized; }
        bool isStarted() const { return started; }
        int getOrderCount() const { return order_count.load(); }
        int getTradeCount() const { return trade_count.load(); }
        
    protected:
        virtual void processOrderBook(const std::string& symbol,
                                    const std::vector<std::pair<double, int>>& bids,
                                    const std::vector<std::pair<double, int>>& asks) {
            // 子类实现订单簿处理逻辑
        }
        
        virtual void processTrade(const std::string& symbol, double price, int volume) {
            // 子类实现成交处理逻辑
        }
        
        virtual void processOrder(const std::string& order_id, const std::string& status) {
            // 子类实现订单状态处理逻辑
        }
    };
    
    // 模拟市场做市策略
    struct MarketMakingStrategy : public IHftStrategy {
        double spread_threshold = 0.01;
        int max_position = 1000;
        int current_position = 0;
        
        MarketMakingStrategy() {
            strategy_name = "MarketMaking";
        }
        
        bool init(const std::map<std::string, std::string>& params) override {
            if (!IHftStrategy::init(params)) return false;
            
            auto it = params.find("spread_threshold");
            if (it != params.end()) {
                spread_threshold = std::stod(it->second);
            }
            
            it = params.find("max_position");
            if (it != params.end()) {
                max_position = std::stoi(it->second);
            }
            
            return spread_threshold > 0 && max_position > 0;
        }
        
    protected:
        void processOrderBook(const std::string& symbol,
                            const std::vector<std::pair<double, int>>& bids,
                            const std::vector<std::pair<double, int>>& asks) override {
            if (bids.empty() || asks.empty()) return;
            
            double best_bid = bids[0].first;
            double best_ask = asks[0].first;
            double spread = best_ask - best_bid;
            
            // 简化的做市逻辑
            if (spread > spread_threshold && std::abs(current_position) < max_position) {
                if (current_position < max_position) {
                    placeBuyOrder(symbol, best_bid + 0.001);
                }
                if (current_position > -max_position) {
                    placeSellOrder(symbol, best_ask - 0.001);
                }
            }
        }
        
        void processTrade(const std::string& symbol, double price, int volume) override {
            // 更新持仓
            current_position += volume;  // 简化处理
        }
        
    private:
        void placeBuyOrder(const std::string& symbol, double price) {
            // 模拟下买单
        }
        
        void placeSellOrder(const std::string& symbol, double price) {
            // 模拟下卖单
        }
    };
    
    // 模拟高频策略工厂
    struct HftStrategyFactory {
        std::map<std::string, std::function<std::unique_ptr<IHftStrategy>()>> creators;
        
        void registerStrategy(const std::string& name, 
                            std::function<std::unique_ptr<IHftStrategy>()> creator) {
            creators[name] = creator;
        }
        
        std::unique_ptr<IHftStrategy> createStrategy(const std::string& name) {
            auto it = creators.find(name);
            if (it != creators.end()) {
                return it->second();
            }
            return nullptr;
        }
        
        std::vector<std::string> getAvailableStrategies() const {
            std::vector<std::string> names;
            for (const auto& pair : creators) {
                names.push_back(pair.first);
            }
            return names;
        }
    };
    
    // 测试高频策略工厂
    HftStrategyFactory factory;
    
    // 注册市场做市策略
    factory.registerStrategy("MarketMaking", []() {
        return std::make_unique<MarketMakingStrategy>();
    });
    
    // 创建策略实例
    auto strategy = factory.createStrategy("MarketMaking");
    ASSERT_NE(strategy, nullptr);
    EXPECT_EQ(strategy->strategy_name, "MarketMaking");
    
    // 初始化策略
    std::map<std::string, std::string> params = {
        {"spread_threshold", "0.005"},
        {"max_position", "500"}
    };
    EXPECT_TRUE(strategy->init(params));
    EXPECT_TRUE(strategy->start());
    
    // 测试订单簿处理
    std::vector<std::pair<double, int>> bids = {{4499.5, 100}, {4499.0, 200}};
    std::vector<std::pair<double, int>> asks = {{4500.5, 150}, {4501.0, 250}};
    
    strategy->onOrderBook("SHFE.rb2501", bids, asks);
    strategy->onTrade("SHFE.rb2501", 4500.0, 50);
    strategy->onOrder("order123", "filled");
    
    EXPECT_EQ(strategy->getTradeCount(), 1);
    EXPECT_EQ(strategy->getOrderCount(), 1);
}

// ========== 执行器工厂测试 ==========

/*!
 * \brief 测试执行器工厂功能
 * 
 * \details 模拟WtExeFact模块的执行器创建和管理功能
 */
TEST_F(StrategyAndFactoryTest, TestExecutorFactory) {
    // 模拟执行器接口
    struct IExecutor {
        std::string executor_name;
        std::map<std::string, std::string> config;
        bool initialized = false;
        std::atomic<int> execution_count{0};
        
        virtual ~IExecutor() = default;
        
        virtual bool init(const std::map<std::string, std::string>& cfg) {
            config = cfg;
            initialized = true;
            return true;
        }
        
        virtual bool executeOrder(const std::string& symbol, 
                                const std::string& action,
                                int quantity, double price) {
            if (!initialized) return false;
            
            execution_count++;
            return processExecution(symbol, action, quantity, price);
        }
        
        virtual std::vector<std::string> getExecutionHistory() const {
            // 返回执行历史记录
            return execution_history;
        }
        
        int getExecutionCount() const { return execution_count.load(); }
        
    protected:
        std::vector<std::string> execution_history;
        
        virtual bool processExecution(const std::string& symbol,
                                    const std::string& action,
                                    int quantity, double price) = 0;
    };
    
    // 模拟TWAP执行器
    struct TwapExecutor : public IExecutor {
        int time_slice_seconds = 60;
        int max_slice_quantity = 100;
        
        TwapExecutor() {
            executor_name = "TWAP";
        }
        
        bool init(const std::map<std::string, std::string>& cfg) override {
            if (!IExecutor::init(cfg)) return false;
            
            auto it = cfg.find("time_slice");
            if (it != cfg.end()) {
                time_slice_seconds = std::stoi(it->second);
            }
            
            it = cfg.find("max_slice_qty");
            if (it != cfg.end()) {
                max_slice_quantity = std::stoi(it->second);
            }
            
            return time_slice_seconds > 0 && max_slice_quantity > 0;
        }
        
    protected:
        bool processExecution(const std::string& symbol,
                            const std::string& action,
                            int quantity, double price) override {
            // 模拟TWAP执行逻辑
            int remaining = quantity;
            while (remaining > 0) {
                int slice_qty = std::min(remaining, max_slice_quantity);
                
                std::string execution_record = action + " " + std::to_string(slice_qty) + 
                                             " " + symbol + " @" + std::to_string(price);
                execution_history.push_back(execution_record);
                
                remaining -= slice_qty;
                
                // 模拟时间切片等待
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
            
            return true;
        }
    };
    
    // 模拟执行器工厂
    struct ExecutorFactory {
        std::map<std::string, std::function<std::unique_ptr<IExecutor>()>> creators;
        
        void registerExecutor(const std::string& name,
                            std::function<std::unique_ptr<IExecutor>()> creator) {
            creators[name] = creator;
        }
        
        std::unique_ptr<IExecutor> createExecutor(const std::string& name) {
            auto it = creators.find(name);
            if (it != creators.end()) {
                return it->second();
            }
            return nullptr;
        }
        
        std::vector<std::string> getAvailableExecutors() const {
            std::vector<std::string> names;
            for (const auto& pair : creators) {
                names.push_back(pair.first);
            }
            return names;
        }
    };
    
    // 测试执行器工厂
    ExecutorFactory factory;
    
    // 注册TWAP执行器
    factory.registerExecutor("TWAP", []() {
        return std::make_unique<TwapExecutor>();
    });
    
    auto executor = factory.createExecutor("TWAP");
    ASSERT_NE(executor, nullptr);
    EXPECT_EQ(executor->executor_name, "TWAP");
    
    // 配置执行器
    std::map<std::string, std::string> config = {
        {"time_slice", "30"},
        {"max_slice_qty", "50"}
    };
    EXPECT_TRUE(executor->init(config));
    
    // 执行订单
    EXPECT_TRUE(executor->executeOrder("SHFE.rb2501", "BUY", 150, 4500.0));
    EXPECT_EQ(executor->getExecutionCount(), 1);
    
    // 验证执行历史
    auto history = executor->getExecutionHistory();
    EXPECT_EQ(history.size(), 3);  // 150/50 = 3个切片
    
    for (const auto& record : history) {
        EXPECT_TRUE(record.find("BUY") != std::string::npos);
        EXPECT_TRUE(record.find("SHFE.rb2501") != std::string::npos);
    }
}

// ========== 风险管理工厂测试 ==========

/*!
 * \brief 测试风险管理工厂功能
 * 
 * \details 模拟WtRiskMonFact模块的风险管理创建和监控功能
 */
TEST_F(StrategyAndFactoryTest, TestRiskManagerFactory) {
    // 模拟风险管理器接口
    struct IRiskManager {
        std::string risk_manager_name;
        std::map<std::string, double> risk_limits;
        std::map<std::string, double> current_exposure;
        bool initialized = false;
        std::atomic<int> violation_count{0};
        
        virtual ~IRiskManager() = default;
        
        virtual bool init(const std::map<std::string, double>& limits) {
            risk_limits = limits;
            initialized = true;
            return true;
        }
        
        virtual bool checkRisk(const std::string& symbol, 
                             const std::string& action,
                             int quantity, double price) {
            if (!initialized) return false;
            
            return performRiskCheck(symbol, action, quantity, price);
        }
        
        virtual void updateExposure(const std::string& symbol, double exposure) {
            current_exposure[symbol] = exposure;
        }
        
        virtual double getCurrentExposure(const std::string& symbol) const {
            auto it = current_exposure.find(symbol);
            return (it != current_exposure.end()) ? it->second : 0.0;
        }
        
        int getViolationCount() const { return violation_count.load(); }
        
    protected:
        virtual bool performRiskCheck(const std::string& symbol,
                                    const std::string& action,
                                    int quantity, double price) = 0;
    };
    
    // 模拟仓位风险管理器
    struct PositionRiskManager : public IRiskManager {
        double max_position_ratio = 0.1;  // 最大仓位比例
        double total_capital = 1000000.0;  // 总资金
        
        PositionRiskManager() {
            risk_manager_name = "PositionRisk";
        }
        
        bool init(const std::map<std::string, double>& limits) override {
            if (!IRiskManager::init(limits)) return false;
            
            auto it = limits.find("max_position_ratio");
            if (it != limits.end()) {
                max_position_ratio = it->second;
            }
            
            it = limits.find("total_capital");
            if (it != limits.end()) {
                total_capital = it->second;
            }
            
            return max_position_ratio > 0 && total_capital > 0;
        }
        
    protected:
        bool performRiskCheck(const std::string& symbol,
                            const std::string& action,
                            int quantity, double price) override {
            double order_value = quantity * price;
            double current_exp = getCurrentExposure(symbol);
            double new_exposure = current_exp;
            
            if (action == "BUY") {
                new_exposure += order_value;
            } else if (action == "SELL") {
                new_exposure -= order_value;
            }
            
            double exposure_ratio = std::abs(new_exposure) / total_capital;
            
            if (exposure_ratio > max_position_ratio) {
                violation_count++;
                return false;  // 风险违规
            }
            
            return true;  // 风险检查通过
        }
    };
    
    // 模拟风险管理工厂
    struct RiskManagerFactory {
        std::map<std::string, std::function<std::unique_ptr<IRiskManager>()>> creators;
        
        void registerRiskManager(const std::string& name,
                                std::function<std::unique_ptr<IRiskManager>()> creator) {
            creators[name] = creator;
        }
        
        std::unique_ptr<IRiskManager> createRiskManager(const std::string& name) {
            auto it = creators.find(name);
            if (it != creators.end()) {
                return it->second();
            }
            return nullptr;
        }
        
        std::vector<std::string> getAvailableRiskManagers() const {
            std::vector<std::string> names;
            for (const auto& pair : creators) {
                names.push_back(pair.first);
            }
            return names;
        }
    };
    
    // 测试风险管理工厂
    RiskManagerFactory factory;
    
    // 注册仓位风险管理器
    factory.registerRiskManager("PositionRisk", []() {
        return std::make_unique<PositionRiskManager>();
    });
    
    auto risk_mgr = factory.createRiskManager("PositionRisk");
    ASSERT_NE(risk_mgr, nullptr);
    EXPECT_EQ(risk_mgr->risk_manager_name, "PositionRisk");
    
    // 配置风险管理器
    std::map<std::string, double> limits = {
        {"max_position_ratio", 0.05},  // 5%最大仓位
        {"total_capital", 2000000.0}   // 200万资金
    };
    EXPECT_TRUE(risk_mgr->init(limits));
    
    // 测试风险检查
    // 正常订单（不超过风险限制）
    EXPECT_TRUE(risk_mgr->checkRisk("SHFE.rb2501", "BUY", 20, 4500.0));  // 90,000元，4.5%
    EXPECT_EQ(risk_mgr->getViolationCount(), 0);
    
    // 更新仓位
    risk_mgr->updateExposure("SHFE.rb2501", 90000.0);
    EXPECT_EQ(risk_mgr->getCurrentExposure("SHFE.rb2501"), 90000.0);
    
    // 超限订单（超过风险限制）
    EXPECT_FALSE(risk_mgr->checkRisk("SHFE.rb2501", "BUY", 30, 4500.0));  // 再加135,000元会超过5%
    EXPECT_EQ(risk_mgr->getViolationCount(), 1);
    
    // 卖出订单（减少仓位）
    EXPECT_TRUE(risk_mgr->checkRisk("SHFE.rb2501", "SELL", 10, 4500.0));  // 减少45,000元
    EXPECT_EQ(risk_mgr->getViolationCount(), 1);  // 违规计数不变
} 